import { IQuestion } from './Model/Question'
import { IAnswerChecker } from './Controler/Anserchecker/IAnswerChecker'
import { GuessNumQuestionBuilder } from './Controler/QuestionBuilder/GuessNumQuestionBuilder'
import { GuessNumAnswerChecker } from './Controler/Anserchecker/GuessNumAnswerChecker'
import { DefaultAnswer, IAnswer } from './Model/Answer'
import { DefaultCheckResponse, ICheckResponse } from './Model/CheckResponse'
import Readline from 'readline'

export class Gamer {
    private readonly question: IQuestion = GuessNumQuestionBuilder.Build();
    private readonly answerChecker: IAnswerChecker = new GuessNumAnswerChecker();
    private readonly answer: IAnswer = new DefaultAnswer();
    private response : ICheckResponse = new DefaultCheckResponse();
    private readline = Readline.createInterface(process.stdin, process.stdout)
    private times = 0

    public Run () {
      console.log('题目已生成请作答')
      this.runReadline()
    }

    private showResponse () {
      if (this.response.IsRight) {
        console.log(this.response.Message)
        console.log('回答正确')
      } else {
        console.log(this.response.Message)
      }
    }

    private showQuestion () {
      console.log(this.question.Question)
    }

    private runReadline () {
      this.readline.question(`[${this.times}] 请输入答案:\n`, answer => { this.gameFlowControl(answer) })
    }

    private gameFlowControl (answer: string) {
      this.answer.Answer = answer

      if (this.answerChecker.Validate(this.answer)) {
        this.times += 1
        this.checkAnswer()
        this.showResponse()

        if (this.response.IsRight) {
          this.readline.pause()
        } else if (this.times >= 8) {
          this.showQuestion()
          this.readline.pause()
        } else {
          this.runReadline()
        }
      } else {
        console.log('输入参数有误')
        this.runReadline()
      }
    }
    //
    // private validateAnswer ():boolean {
    //   return this.answerChecker.Validate(this.answer)
    // }

    private checkAnswer () {
      if (this.answer) {
        this.response = this.answerChecker.Check(this.question, this.answer)
      } else {
        console.error('没有输入答案')
      }
    }
}
